package Games;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

/**
 * 贪吃蛇游戏面板
 */
public class SnakePanel extends JPanel implements KeyListener, ActionListener {

    Snake snk = null;
    Timer timer = new Timer(100,this);  //绑定定时器
    int x_width = 0, x_height = 0;

    public SnakePanel(int width, int height){
        this.setFocusable(true);
        this.addKeyListener(this);  //添加按键监听

        x_width = width;
        x_height = height;
        snk = new Snake(x_width / 10, x_height / 10);
        timer.start();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        //绘制背景
        g.fillRect(0, 0, x_width, x_height);
        //绘制蛇身
        g.setColor(Color.GREEN);
        for(Point p: snk.Nodes){
            g.fillRect(p.y * 10, p.x * 10, 9, 9);
        }
        //绘制食物
        g.setColor(Color.YELLOW);
        g.fillRect(snk.Food.y * 10, snk.Food.x * 10, 9,9);
    }

    @Override
    public void keyTyped(KeyEvent e) {
        //打字时
    }

    @Override
    public void keyPressed(KeyEvent e) {
//        System.out.println(e.getKeyCode());
        switch (e.getKeyCode()){
            case 37: this.snk.SetDirection(Direction.Left); break;
            case 38: this.snk.SetDirection(Direction.Up); break;
            case 39: this.snk.SetDirection(Direction.Right); break;
            case 40: this.snk.SetDirection(Direction.Down); break;
            default: break;
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        //运行判断
        if(this.timer.isRunning())
            return;
        //重新开始
        snk.Reset();
        timer.start();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        try{
            this.snk.Move();
            this.repaint();
        }
        catch (Exception ex){
            //停止游戏
            this.timer.stop();
            //打印提示
            String msg = ex.getMessage() + "（按空格键重新开始）";
            System.out.println(msg);
            //绘制结束界面
            Graphics g = this.getGraphics();
            g.setFont(new Font("微软雅黑", Font.PLAIN, 18));
            int msg_width = g.getFontMetrics().stringWidth(msg);
            int msg_height = g.getFontMetrics().getHeight();
            int x = (x_width - msg_width) / 2;
            int y = (x_height - msg_height) / 2;
            g.setColor(Color.WHITE);
            g.drawString(msg, x, y);
        }
    }
}
